// src/views/login/Index.tsx
import { Form, Input, Button, message } from 'antd'
import {
UserOutlined,
LockOutlined
} from '@ant-design/icons';
// 导入封装好的接口
import { IAdminParams,adminLoginFn } from '../../api/user';

// RTK相关
import { useAppDispatch } from "../../store/hooks";
import { changeAdminName, changeCheckedkeys,changeLoginState, changeRole, changeToken } from "../../store/modules/user";
import { useNavigate, useLocation } from 'react-router-dom';
type IndexProps = {}

const Login = (props: IndexProps) => {
const dispatch = useAppDispatch()
const navigate = useNavigate()
// 登录之后的参数
const {search} = useLocation()
const redirectUrl = search.split('?r=')[1]
const onFinish = (values: IAdminParams) => {
 console.log(values)
 adminLoginFn(values).then(res => {
  console.log(res.data)
  switch (res.data.code) {
    case '10005':
      message.error('不存在该账户')
      break;
    case '10003':
      message.error('密码错误')
      break;
    default:
      message.success('登录成功')
      // 在 RTK 中存储信息到本地进行状态管理
      const result = res.data.data
      dispatch(changeLoginState(true))
      dispatch(changeAdminName(result.adminname))
      dispatch(changeToken(result.token))
      dispatch(changeRole(result.role))
      dispatch(changeCheckedkeys(result.checkedkeys))
      // 跳转到用户退出之前的位置，没有就到首页
      redirectUrl ? navigate(redirectUrl,{replace:true}) : navigate('/',{replace:true})
      break;
  }
})
}
return (
 <div id='components-form-demo-normal-login'>
   <Form
     name="normal_login"
     className="login-form"
     initialValues={{ remember: true }}
     onFinish={onFinish}
   >
     <h1>嗨购管理系统</h1>
     <Form.Item
       name="adminname"
       rules={[{ required: true, message: '请输入管理员账户!' }]}
     >
       <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="管理员账户" allowClear />
     </Form.Item>
     <Form.Item
       name="password"
       rules={[{ required: true, message: '请输入密码!' }]}
     >
       <Input
         prefix={<LockOutlined className="site-form-item-icon" />}
         type="password"
         placeholder="密码"
         allowClear
       />
     </Form.Item>

     <Form.Item>
       <Button type="primary" htmlType="submit" className="login-form-button">
         登 录
       </Button>
     </Form.Item>
   </Form>
 </div>
)
}
export default Login